package com.infore.airsupervise.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.infore.airsupervise.bean.LawingSiteE;
import com.infore.airsupervise.bean.PolluterE;
import com.infore.airsupervise.utils.JSONUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaotao on 2017/6/2.
 */

public class SiteLawDBHelper extends MyOpenHelper<LawingSiteE> {
    private String tableName;
    private String userId ;

    public SiteLawDBHelper(Context context, int version ,String userId) {
        super(context, version);
        this.userId = userId;
        tableName = LawingSiteE.class.getName().replaceAll("\\.","_");
    }


    @Override
    protected void createTable(Class table) {
        if(!isTableExist(table)){
             tableName = table.getName().replaceAll("\\.","_");
            SQLiteDatabase db = getWritableDatabase(); //获取一个可写的数据库操作实例
            StringBuilder str_builder = new StringBuilder();
            str_builder.append("create table IF NOT EXISTS "+tableName+"(");
            //主键
            str_builder.append("_id Integer PRIMARY KEY AUTOINCREMENT" +
                    ",id Integer" +
                    ",missionId varchar" +
                    ",mn varchar" +
                    ",name varchar" +
                    ",time_b varchar" +
                    ",recorderJCList text" +
                    ",notesJCList text" +
                    ",notesAskList text" +
                    ",evidence text" +
                    ",signatureCom text" +
                    ",signaturePson text" +
                    ",userId varchar"+
                    ",polluterE text);");
            db.execSQL(str_builder.toString());
        }
    }


    @Override
    public void save(LawingSiteE lawingSiteE) {
        String tableName = LawingSiteE.class.getName().replaceAll("\\.","_");
       SQLiteDatabase db =  getWritableDatabase();
        createTable(lawingSiteE.getClass());
        ContentValues contentValues = initData(lawingSiteE);
        db.replace(tableName,null,contentValues);
    }

    @Override
    public void saveAll(List<LawingSiteE> list) {
        //如果集合为空直接不需要操作
        if (list.isEmpty()) {
            return;
        }
        String tableName = LawingSiteE.class.getName().replaceAll("\\.","_");
        SQLiteDatabase db = getWritableDatabase();
        createTable(LawingSiteE.class);
        db.beginTransaction();
        for (LawingSiteE siteE : list) {
            ContentValues contentValues = initData(siteE);
            db.replace(tableName,null,contentValues);
        }
        //设置事务为成功状态
        db.setTransactionSuccessful();
        //当事务结束，才会一次性执行上面for中的所有save方法，如果该事务没有结束，则for中的save方法一个都不会执行
        db.endTransaction();
    }

    @Override
    public List<LawingSiteE> queryAll() {
        if(!isTableExist(LawingSiteE.class)){
            return new ArrayList<>();
        }
        SQLiteDatabase db = getReadableDatabase();
        //通过表名查询所有的数据
        String tableName = LawingSiteE.class.getName().replaceAll("\\.","_");
        //默认值只查找对应用户id的数据
        Cursor cursor = db.query(tableName, null, "userId = ?", new String[]{userId}, null, null, null);
        List<LawingSiteE> list = getData(cursor);
        cursor.close();
        db.close();
        return list;
    }

    @Override
    public void updata(LawingSiteE lawingSiteE) {
        if(null == lawingSiteE){
            return ;
        }
        if(!isTableExist(LawingSiteE.class)){
            return ;
        }
        SQLiteDatabase db = getWritableDatabase();
        String tableName = LawingSiteE.class.getName().replaceAll("\\.","_");
        ContentValues contentValues = initData(lawingSiteE);
        db.update(tableName,contentValues,"_id = ?",new String[]{lawingSiteE.get_id()+""});
        db.close();
    }

    /**
     *
     * @param lawingSiteE
     */
    @Override
    public void delete(LawingSiteE lawingSiteE) {
        if(null == lawingSiteE){
            return ;
        }
        //根据_id删除对应数据
        SQLiteDatabase db = getWritableDatabase();
        toDelete(lawingSiteE.get_id(),db);
        db.close();
    }

    @Override
    public void deleteAll(List<LawingSiteE> list) {
        if(null != list && list.size() > 0){
            SQLiteDatabase db = getWritableDatabase();
            db.beginTransaction();
            for( LawingSiteE e : list){
                toDelete(e.get_id(),db);
            }
            db.setTransactionSuccessful();
            db.endTransaction();
            db.close();
        }
    }


    /**
     * 初始化数据
     * @param lawingSiteE
     * @return
     */
    private ContentValues initData(LawingSiteE lawingSiteE){
        //将一个对象中的所有字段添加到该数据集中
        ContentValues contentValues = new ContentValues();
        contentValues.put("id",lawingSiteE.getId());
        contentValues.put("missionId",lawingSiteE.getMissionId());
        contentValues.put("mn",lawingSiteE.getMn());
        contentValues.put("time_b",lawingSiteE.getTime());
        contentValues.put("name",lawingSiteE.getName());
        contentValues.put("userId",userId);
        String str_evidence = JSONUtil.toJSOnString(lawingSiteE.getEvidence());
        contentValues.put("evidence",str_evidence);
        String str_polluterE = JSONUtil.toJSOnString(lawingSiteE.getPolluterE());
        contentValues.put("polluterE" ,str_polluterE);
        String str_signatureCom = JSONUtil.toJSONString(lawingSiteE.getSignatureCom());
        contentValues.put("signatureCom",str_signatureCom);
        String str_signaturePson = JSONUtil.toJSONString(lawingSiteE.getSignaturePson());
        contentValues.put("signaturePson",str_signaturePson);
        String str_notesAskList = JSONUtil.toJSONString(lawingSiteE.getNotesAskList());
        contentValues.put("notesAskList",str_notesAskList);
        String str_recorderJCList = JSONUtil.toJSONString(lawingSiteE.getRecorderJCList());
        contentValues.put("recorderJCList",str_recorderJCList);
        String str_notesJCList = JSONUtil.toJSONString(lawingSiteE.getNotesJCList());
        contentValues.put("notesJCList",str_notesJCList);
        return contentValues;
    }

    private List<LawingSiteE> getData(Cursor cursor){
        List<LawingSiteE> list = new ArrayList<>();
        while (cursor.moveToNext()){
            LawingSiteE siteE = new LawingSiteE();
            if(cursor.getColumnIndex("_id") != -1){
                siteE.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            }
            if( cursor.getColumnIndex("id")!= -1){
                siteE.setId(cursor.getInt(cursor.getColumnIndex("id")));
            }
            if(cursor.getColumnIndex("missionId")!= -1){
                siteE.setMissionId(cursor.getString(cursor.getColumnIndex("missionId")));
            }
            if(cursor.getColumnIndex("mn")!= -1){
                siteE.setMn(cursor.getString(cursor.getColumnIndex("mn")));
            }
            if(cursor.getColumnIndex("time_b")!= -1){
                siteE.setTime(cursor.getString(cursor.getColumnIndex("time_b")));
            }
            if(cursor.getColumnIndex("name") != -1){
                siteE.setName(cursor.getString(cursor.getColumnIndex("name")));
            }
            if(cursor.getColumnIndex("evidence")!= -1){
                String str_evidence = cursor.getString(cursor.getColumnIndex("evidence"));
                LawingSiteE.Evidence evidence = JSONUtil.parseJSONString(str_evidence,LawingSiteE.Evidence.class);
                siteE.setEvidence(evidence);
            }
            if(cursor.getColumnIndex("polluterE") != -1){
                String str_polluterE = cursor.getString(cursor.getColumnIndex("polluterE"));
                PolluterE polluterE = JSONUtil.parseJSONString(str_polluterE,PolluterE.class);
                siteE.setPolluterE(polluterE);
            }
            if(cursor.getColumnIndex("signatureCom")!= -1){
                String str_signatureCom = cursor.getString(cursor.getColumnIndex("signatureCom"));
                List<String> list_signatureCom = JSONUtil.parseJSONArrayString(str_signatureCom,String.class);
                siteE.setSignatureCom(list_signatureCom);
            }
            if(cursor.getColumnIndex("signaturePson") != -1){
                String str_signaturePson = cursor.getString(cursor.getColumnIndex("signaturePson"));
                List<String> list_signaturePson = JSONUtil.parseJSONArrayString(str_signaturePson,String.class);
                siteE.setSignaturePson(list_signaturePson);
            }
            if(cursor.getColumnIndex("notesAskList") != -1){
                String str_notesAskList = cursor.getString(cursor.getColumnIndex("notesAskList"));
                List<LawingSiteE.NotesAsk> notesAskList = JSONUtil.parseJSONArrayString(str_notesAskList,LawingSiteE.NotesAsk.class);
                siteE.setNotesAskList(notesAskList);
            }
            if(cursor.getColumnIndex("recorderJCList") != -1){
                String str_recorderJCList = cursor.getString(cursor.getColumnIndex("recorderJCList"));
                List<LawingSiteE.RecorderJC> recorderJCList = JSONUtil.parseJSONArrayString(str_recorderJCList,LawingSiteE.RecorderJC.class);
                siteE.setRecorderJCList(recorderJCList);
            }
            if(cursor.getColumnIndex("notesJCList") != -1){
                String str_notesJCList = cursor.getString(cursor.getColumnIndex("notesJCList"));
                List<LawingSiteE.NotesJC> notesJCList = JSONUtil.parseJSONArrayString(str_notesJCList,LawingSiteE.NotesJC.class);
                siteE.setNotesJCList(notesJCList);
            }
            list.add(siteE);
        }
        return list;
    }

    /**
     *
     * @param id
     * @param db
     */
    private void toDelete(int id , SQLiteDatabase db){
        db.delete(tableName,"_id = ?",new String[]{id+""});
    }

    public void clearTable(){
        String tableName = LawingSiteE.class.getName().replaceAll("\\.","_");
        clear(tableName);
    }

}
